package com.ada.files;

import java.io.IOException;
import java.nio.file.*;

public class FolderWatcher {
    public static void main(String[] args) {
        try {
            // 创建WatchService对象
            WatchService watchService = FileSystems.getDefault().newWatchService();

            // 注册要监视的目录
            Path folderPath = Paths.get("E:\\迅雷下载");
            folderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

            // 启动无限循环，等待事件发生
            while (true) {
                WatchKey key;
                try {
                    // 等待监视事件
                    key = watchService.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }

                // 处理监视事件
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();

                    // 处理不同类型的事件
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("文件创建：" + event.context());
                    } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("文件删除：" + event.context());
                    } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("文件修改：" + event.context());
                    }
                }

                // 重置WatchKey，以便继续接收事件
                boolean valid = key.reset();
                if (!valid) {
                    break; // 如果WatchKey无效，退出循环
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
